package KoebuBot;


use strict;
use warnings;
use lib '/root/.cpan/build/Net-Twitter-3.17001-NYTlxk/lib/';
use Net::Twitter::Lite;
use DBI();
binmode(STDOUT, ":utf8");


sub new{
    my $class = shift;
    my $args = shift;
    my $twit = Net::Twitter::Lite->new(
        traits              => [qw/api::rest oauth/],
        consumer_key        => 'viDhkCJfv6ZvwztUoCo0Q',
        consumer_secret     => 'nHvQpO5gWO4p0KncSRBzmFylSSXLchNxxdWlLYENqQ',
        access_token        => '357431450-g3umuuJ9glcBx4yRBaCNQbIxnsI5lxvAU8YePNKU',
        access_token_secret => 'M96rJJb14gKLtvZzKWLwsHNHFgSwpOER6SlFYfGY0',
    );
    my $self = bless { twit => $twit },$class;
    return $self;
}


sub mention{
    my $self = shift;
    my $twit = $self->{ twit };
    my $mentions = $twit->mentions();
    return $mentions;
}


sub connect_db{
    my $self = shift;
    my $dbh = DBI->connect("DBI:mysql:database=twitter;host=localhost","yasumoto","48FnSrCX", {'RaiseError' => 1});
    return $dbh;
}


sub relational_id{
    my $self = shift;
    my $mentions_ref= $self->mention;
    my @save_list = ();
    my $dbh = $self->connect_db;
    for my $mention_ref ( @$mentions_ref ){
        my $tweet_id = $mention_ref->{id}; 
        my $sth = $dbh->prepare("select tweet_id from mention where tweet_id = $tweet_id");
        $sth->execute();
        my @row = $sth->fetchrow_array;
        if (@row) {
        #次のキーを調べる;
        }else {
        push ( @save_list, $mention_ref );
        }
    }
    my $save_list_ref = \@save_list;
    return $save_list_ref;
}


sub reply{
    my $self = shift;
    my $twit = $self->{ twit };
    my $mentions_ref = $self->relational_id;
    for my $reply_mention ( @$mentions_ref ){
        my $reply_to = $reply_mention->{user}{screen_name};
        my @send_word = ("@".$reply_to." こんにちは","@".$reply_to." こんばんは","@".$reply_to." さよなら","@".$reply_to." また明日");
        my $word_num = @send_word;
        my $rand_num = int rand($word_num);
        my $selected_word = utf8::decode( $send_word[$rand_num] );
        $selected_word = "@".$reply_to." hello";
        $twit->update( "$selected_word" );
        print "$selected_word";
    }
}


sub save{
    my $self = shift;
    my $save_list_ref = $self->relational_id;
    my $dbh = $self->connect_db;
    for my $save_mention ( @$save_list_ref ){
        my $save_id = $save_mention->{id};
        my $save_text = $save_mention->{text};
        $dbh->do("insert into mention( tweet_id, text )values(\"$save_id\",\"$save_text\")");
    }
    my $get_num = @$save_list_ref; 
    print $get_num;
}



1;
